package com.zs.demo.shiro;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import java.io.Serializable;

/* @Desc: 解决单次请求需要多次访问redis
 * @author:zhengs  
 * @Time: 2018/11/23 14:09
 * @Copyright: © zhengs 版权所有  
 * @Warning: 本内容仅限于本公司内部传阅,禁止外泄或用于其它商业目的  
 */
public class MySessionManager extends DefaultWebSessionManager {
    private static Logger logger = LoggerFactory.getLogger(DefaultWebSessionManager.class);
    
    /* @Desc: 获取session,优化单次请求需要多次访问redis
     * @author:zhengs  
     * @Time: 2018/11/23 14:11
     * @Copyright: © zhengs 版权所有  
     * @Warning: 本内容仅限于本公司内部传阅,禁止外泄或用于其它商业目的  
     */
    @Override
    protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
        Serializable sessionId = getSessionId(sessionKey);
        ServletRequest request = null;

        if (sessionKey instanceof WebSessionKey) {
            request = ((WebSessionKey) sessionKey).getServletRequest();
        }
        // 1.从request中读取session
        if (request != null && null != sessionId) {
            Object sessionObj = request.getAttribute(sessionId.toString());
            if (sessionObj != null) {
                logger.debug("read session from request");
                return (Session) sessionObj;
            }
        }

        // 2.从redis中读取session
        Session session = super.retrieveSession(sessionKey);
        if (request != null && null != sessionId) {
            request.setAttribute(sessionId.toString(), session);
        }
        
        return session;
    }
}